import { Request, Response } from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import mysql from 'mysql2/promise';

// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'DHY963dlm',
  database: 'aiteach'
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 定义允许的文件类型
const ALLOWED_TYPES = {
  'application/vnd.ms-powerpoint': '.ppt',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx',
  'application/pdf': '.pdf'
} as const;

type AllowedMimeType = keyof typeof ALLOWED_TYPES;

// 配置文件存储
const storage = multer.diskStorage({
  destination: (_req: Request, _file: Express.Multer.File, cb) => {
    const uploadDir = path.join(process.cwd(), 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (_req: Request, file: Express.Multer.File, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    // 解码原始文件名
    const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');
    const ext = path.extname(originalName).toLowerCase();
    // 使用解码后的文件名
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});

// 增强的文件类型验证
const fileFilter = (_req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  console.log('文件信息:', {
    name: file.originalname,
    type: file.mimetype,
    size: file.size
  });

  // 检查文件类型
  if (!(file.mimetype in ALLOWED_TYPES)) {
    console.error('不支持的文件类型:', file.mimetype);
    return cb(new Error('不支持的文件类型'));
  }

  // 检查文件扩展名
  const ext = path.extname(file.originalname).toLowerCase();
  if (ext !== ALLOWED_TYPES[file.mimetype as AllowedMimeType]) {
    console.error('文件扩展名与类型不匹配:', ext, file.mimetype);
    return cb(new Error('文件扩展名与类型不匹配'));
  }

  // 检查文件大小
  const maxSize = 50 * 1024 * 1024; // 50MB
  if (file.size > maxSize) {
    console.error('文件大小超过限制:', file.size);
    return cb(new Error('文件大小超过限制(50MB)'));
  }

  cb(null, true);
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 50 * 1024 * 1024 // 限制50MB
  }
});

// 文件清理函数
const cleanupOldFiles = async () => {
  const uploadDir = path.join(process.cwd(), 'uploads');
  const maxAge = 24 * 60 * 60 * 1000; // 24小时

  try {
    const files = await fs.promises.readdir(uploadDir);
    const now = Date.now();

    for (const file of files) {
      const filePath = path.join(uploadDir, file);
      const stats = await fs.promises.stat(filePath);
      
      if (now - stats.mtime.getTime() > maxAge) {
        await fs.promises.unlink(filePath);
        console.log(`已删除过期文件: ${file}`);
      }
    }
  } catch (error) {
    console.error('文件清理失败:', error);
  }
};

// 定期清理文件
setInterval(cleanupOldFiles, 60 * 60 * 1000); // 每小时执行一次

export const uploadFile = async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      console.error('没有上传文件');
      return res.status(400).json({
        success: false,
        message: '没有上传文件'
      });
    }

    // 验证文件完整性
    const stats = await fs.promises.stat(req.file.path);
    if (stats.size === 0) {
      console.error('文件上传不完整');
      await fs.promises.unlink(req.file.path);
      return res.status(400).json({
        success: false,
        message: '文件上传不完整'
      });
    }

    // 解码原始文件名
    const originalName = Buffer.from(req.file.originalname, 'latin1').toString('utf8');

    // 保存到数据库
    const connection = await pool.getConnection();
    try {
      await connection.execute(
        'INSERT INTO presentations (filename, original_name, file_size, mime_type, file_path) VALUES (?, ?, ?, ?, ?)',
        [
          req.file.filename,
          originalName,
          req.file.size,
          req.file.mimetype,
          req.file.path
        ]
      );
    } finally {
      connection.release();
    }

    console.log('文件上传成功:', {
      name: originalName,
      size: req.file.size,
      path: req.file.path
    });

    res.json({
      success: true,
      data: {
        name: originalName,
        size: req.file.size,
        type: req.file.mimetype,
        url: `/uploads/${req.file.filename}`
      }
    });
  } catch (error) {
    console.error('文件上传失败:', error);
    // 如果上传失败,清理临时文件
    if (req.file && req.file.path) {
      try {
        await fs.promises.unlink(req.file.path);
      } catch (unlinkError) {
        console.error('清理临时文件失败:', unlinkError);
      }
    }
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '文件上传失败'
    });
  }
};

// 获取所有PPT文件列表
export const getPresentations = async (req: Request, res: Response) => {
  try {
    const connection = await pool.getConnection();
    try {
      const [rows] = await connection.execute('SELECT * FROM presentations ORDER BY upload_time DESC');
      res.json({
        success: true,
        data: rows
      });
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('获取文件列表失败:', error);
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '获取文件列表失败'
    });
  }
}; 